package com.gexin.controller.system.coupon;

import com.gexin.common.model.ApiResponse;
import com.gexin.common.utils.IdGenerateUtils;
import com.gexin.common.utils.OtherUtil;
import com.gexin.common.utils.StringUtil;
import com.gexin.core.web.SystemBaseController;
import com.gexin.model.activity.Coupon;
import com.gexin.model.product.ProductType;
import com.gexin.model.product.Products;
import com.gexin.model.user.UserCoupon;
import com.gexin.service.conpon.CouponService;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.template.expr.ast.Id;

import java.util.Date;

@ControllerBind(controllerKey = "/system/coupon", viewPath = "WEB-INF/system/coupon/")
public class CouponController extends SystemBaseController {

	public void index(){
		if(isAjax()){
			Page<Coupon> list = CouponService.dao.findList(getpage() , getpageSize());
			renderJson(list);
			return;
		}
		setAttr("products", Products.dao.findNormalProductAll());
		setAttr("productTypes", ProductType.dao.findAll());
		render("coupon.html");
	}

	public void save(){
		Coupon coupon = getModel(Coupon.class , "coupon");
		//使用时间
		String useTime = getPara("useTime");
		if (StringUtil.isBlank(useTime)){
			fail("使用时间不能为null!");
			return ;
		}
		//发放时间
		String outOfTime = getPara("outOfTime");
		if (StringUtil.isBlank(outOfTime)){
			fail("使用时间不能为null!");
			return ;
		}
		String[] useTimes = useTime.split(" - ");
		if(useTimes.length!=2){
			fail("使用时间时间格式错误!");
			return ;
		}
		String[] outOfTimes = outOfTime.split(" - ");
		if(outOfTimes.length!=2){
			fail("使用时间时间格式错误!");
			return ;
		}
		if(coupon.getWithAmount().compareTo(coupon.getUsedAmount())!=1){
			fail("满减的金额必须大于使用的金额!");
			return;
		}
		Date validStartTime = OtherUtil.StrToDate(useTimes[0] , "yyyy-MM-dd");
		Date validEndTime = OtherUtil.StrToDate(useTimes[1] , "yyyy-MM-dd");
		coupon.setValidStartTime(validStartTime);
		coupon.setValidEndTime(validEndTime);
		Date startTime = OtherUtil.StrToDate(outOfTimes[0] , "yyyy-MM-dd");
		coupon.setStartTime(startTime);
		Date endTime = OtherUtil.StrToDate(outOfTimes[1] , "yyyy-MM-dd");
		coupon.setEndTime(endTime);

		ApiResponse apiResponse = new ApiResponse();
		if(StringUtil.isBlank(coupon.getId())){
			coupon.setCreateTime(new Date());
			coupon.setCreateUser(getLoginUserId());
			coupon.setId(IdGenerateUtils.getId());
			boolean save = coupon.save();
			apiResponse = new ApiResponse(save,save?"保存成功!":"保存失败!");
		}else{
			boolean update = coupon.update();
			apiResponse = new ApiResponse(update,update?"更新成功!":"更新失败!");
		}
		renderJson(apiResponse);
	}

	/**
	 * 删除优惠券
	 */
	public void deleteCoupon(){
		String id = getPara();
		ApiResponse apiResponse = CouponService.dao.deleteCouponById(id);
		renderJson(apiResponse);
	}



}
